package main

import (
	"fmt"
	"time"
)

func worker(id int, c <-chan int)  {
	for {
		fmt.Printf("worker %d received %c \n", id, <-c)
	}
}

func chanDemo()  {
	//var channels [10]chan int   //数组
	var channels [10]chan <-  int   //数组
	//channels := make(chan [10]int)
	for i := 0; i < 10; i++ {
		//channels[i] = make(chan int)
		//go worker(i, channels[i])
		channels[i] = creatWorker(i)

	}
	for i := 0; i < 10; i++ {
		channels[i] <- 'a' + i
	}
	for i := 0; i < 10; i++ {
		channels[i] <- 'A' + i
	}
	time.Sleep(time.Millisecond)
}

//channel 当做返回值
func creatWorker(id int) chan <- int{ //返回的channel只能接受数据 是单向channel
	c := make(chan int)
	go func() {
		for {
			fmt.Printf("worker %d received %c\n", id, <-c)
		}
	}()
	return c
}

func channelDemo()  {
	c := make(chan int)
	go func() {
		for {
			n := <-c
			fmt.Println(n)
		}
	}()
	c <- 1
	c <- 2
	time.Sleep(time.Millisecond)
}
//带缓冲的channel
func bufferChanel() {
	c := make(chan int, 4) //声明带缓冲的channel
	go bufferWorker(0, c)
	c <- 'a'
	c <- 'b'
	c <- 'b'
	c <- 'c'
	//c <- 5  //超过缓存区会报错
	time.Sleep(time.Millisecond)
}

func bufferWorker(id int, c chan int)  {
	for {
		if n, ok := <-c; ok { //判断channel为空
			fmt.Printf("worker %d received %c \n", id, n)
		}
		for n := range c { //判断channel为空
			fmt.Printf("worker %d received %c \n", id, n)
		}
	}
}

func createBufferWorker(id int) chan<- int {
	c := make(chan int)
	go bufferWorker(id, c)
	return c
}

//关闭channel
func channelClose()  {
	c := make(chan int, 4) //声明带缓冲的channel
	go bufferWorker(0, c)
	c <- 'a'
	c <- 'b'
	c <- 'b'
	c <- 'c'
	close(c) //只能发送方close 关闭channel 关闭之后还是会收到类型的空值 0、空字符串
	time.Sleep(time.Millisecond)
}

func main() {
	//channelDemo()
	//chanDemo()
	//bufferChanel()
	channelClose()
}
